# coding=utf-8

from html.parser import HTMLParser


class AttributedTag:
    def __init__(self, name, attrs):
        self.name = name
        self.attrs = attrs


class AttributedTextSegment:
    def __init__(self):
        self.text = ""
        self.range = range(0, 0)
        self.tags = []


class AttributedText:
    def __init__(self):
        self.segments = []


class AttributedTextParser(HTMLParser):

    def __init__(self):
        super(AttributedTextParser, self).__init__()
        self.current_tags = []
        self.current_position = 0
        self.attributed_text = AttributedText()

    def error(self, message):
        pass

    def handle_starttag(self, tag, attrs):
        self.current_tags.append(AttributedTag(tag, attrs))

    def handle_endtag(self, tag):
        if self.current_tags:
            last = self.current_tags[-1]
            if last.name == tag:
                self.current_tags.pop(len(self.current_tags)-1)

    def handle_data(self, data):
        if data:
            segment = AttributedTextSegment()
            segment.text = str(data)
            segment.range = range(self.current_position, self.current_position + len(segment.text))
            segment.tags = self.current_tags.copy()

            self.current_position += len(segment.text)
            self.attributed_text.segments.append(segment)

    def feed(self, data: str):
        super(AttributedTextParser, self).feed(data)
